<template>
  <div class="background-gallery">
    <!-- 顶部操作栏 -->
    <div class="gallery-header">
      <!-- 搜索和筛选 -->
      <div class="search-filter">
        <el-select
            v-model="fileTypeFilter"
            placeholder="文件类型"
            clearable
            @change="handleFilterChange"
            class="filter-select"
        >
          <el-option label="全部" value="" />
          <el-option label="图片" value="image" />
          <el-option label="视频" value="video" />
        </el-select>
      </div>
    </div>

    <!-- 资源列表 -->
    <div v-loading="backgroundStore.loading" class="gallery-content">
      <el-empty v-if="backgrounds.length === 0" description="暂无背景资源" />
      <div v-else class="background-grid">
        <div
            v-for="bg in backgrounds"
            :key="bg.id"
            class="background-item"
            @click="handleSelectBackground(bg)"
        >
          <div class="background-preview">
            <el-image
                v-if="bg.fileType === 'image'"
                :src="bg.url"
                fit="cover"
                class="preview-media"
                loading="lazy"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <video
                v-else
                :src="bg.url"
                class="preview-media"
                preload="metadata"
                muted
                loop
                @mouseover="playVideo($event)"
                @mouseout="pauseVideo($event)"
            ></video>
            <div class="background-actions">
              <el-button
                  type="primary"
                  size="small"
                  circle
                  @click.stop="handleSelectBackground(bg)"
              >
                <el-icon><Select /></el-icon>
              </el-button>
              <el-button
                  type="danger"
                  size="small"
                  circle
                  @click.stop="handleDeleteBackground(bg)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
          <div class="background-info">
            <div class="background-name">{{ bg.name || formatFilename(bg.url) }}</div>
            <div class="background-meta">
              <el-tag size="small" :type="bg.fileType === 'image' ? 'success' : 'warning'">
                {{ bg.fileType === 'image' ? '图片' : '视频' }}
              </el-tag>
              <span class="background-date">{{ formatDate(bg.createTime) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="gallery-pagination">
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          layout="sizes, prev, pager, next, total"
          :total="backgroundStore.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog
        v-model="deleteDialog.visible"
        title="删除背景"
        width="400px"
        :close-on-click-modal="false"
    >
      <div class="delete-confirm">
        <p>确定要删除此背景吗？此操作不可恢复。</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialog.visible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete" :loading="deleteDialog.loading">
            确定删除
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { Search, Upload, Picture, Select, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'
import { getUploadUrl } from '@/utils/uploadConfig.js'
import { useBackgroundStore } from '@/stores/video/background'

const props = defineProps({
  type: {
    type: String,
    default: 'image',
    validator: (value) => ['image', 'video'].includes(value)
  },
  multiSelect: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['select', 'select-multiple'])

// 状态
const backgroundStore = useBackgroundStore()
const fileType = computed(() => props.type)
const searchKeyword = ref('')
const fileTypeFilter = ref(props.type)
const currentPage = ref(1)
const pageSize = ref(12)
const selectedBackgrounds = ref([])
const upload = ref(false)

// 背景列表
const backgrounds = computed(() => backgroundStore.backgrounds)

// 删除对话框状态
const deleteDialog = ref({
  visible: false,
  loading: false,
  background: null
})

// 初始化
onMounted(() => {
  fetchBackgrounds()
})

// 监听文件类型变化
watch(() => props.type, (newType) => {
  fileTypeFilter.value = newType
  fetchBackgrounds()
})

// 获取背景资源列表
const fetchBackgrounds = async () => {
  await backgroundStore.getBackgrounds({
    page: currentPage.value,
    pageSize: pageSize.value,
    type: fileTypeFilter.value,
    keyword: searchKeyword.value
  })
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchBackgrounds()
}

// 筛选处理
const handleFilterChange = () => {
  currentPage.value = 1
  fetchBackgrounds()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchBackgrounds()
}

const handlePageChange = (page) => {
  currentPage.value = page
  fetchBackgrounds()
}

// 上传前验证
const beforeUpload = (file) => {
  upload.value = true
  const isImage = fileType.value === 'image'
  const isVideo = fileType.value === 'video'

  // 检查文件类型
  if (isImage) {
    const isJPG = file.type === 'image/jpeg'
    const isPNG = file.type === 'image/png'
    if (!isJPG && !isPNG) {
      upload.value = false
      ElMessage.error('图片只能是 JPG 或 PNG 格式!')
      return false
    }
  } else if (isVideo) {
    const isMP4 = file.type === 'video/mp4'
    const isWebM = file.type === 'video/webm'
    if (!isMP4 && !isWebM) {
      upload.value = false
      ElMessage.error('视频只能是 MP4 或 WebM 格式!')
      return false
    }
  }

  // 检查文件大小
  const maxSize = 50 * 1024 * 1024 // 50MB
  if (file.size > maxSize) {
    upload.value = false
    ElMessage.error('文件大小不能超过 50MB!')
    return false
  }

  ElMessage.info('开始上传，请稍候...')
  return true
}

// 上传成功处理
const handleUploadSuccess = (response) => {
  if (response.code === 200 && response.data) {
    ElMessage.success('上传成功')
    fetchBackgrounds() // 刷新列表
  } else {
    ElMessage.error(response.message || '上传失败')
  }
  upload.value = false
}

// 上传失败处理
const handleUploadError = (error) => {
  ElMessage.error('上传失败，请稍后重试')
  upload.value = false
}

// 选择背景
const handleSelectBackground = (background) => {
  if (props.multiSelect) {
    // 多选模式
    const index = selectedBackgrounds.value.findIndex(b => b.id === background.id)
    if (index > -1) {
      selectedBackgrounds.value.splice(index, 1)
    } else {
      selectedBackgrounds.value.push(background)
    }
    emit('select-multiple', selectedBackgrounds.value)
  } else {
    // 单选模式
    emit('select', background)
  }
}

// 删除背景
const handleDeleteBackground = (background) => {
  deleteDialog.value.background = background
  deleteDialog.value.visible = true
}

// 确认删除
const confirmDelete = async () => {
  if (!deleteDialog.value.background) return

  deleteDialog.value.loading = true
  try {
    const response = await backgroundStore.removeBackground(deleteDialog.value.background.id)

    if (response.code === 200) {
      ElMessage.success('删除成功')
      // 列表已在 store 内更新，无需手动刷新
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    console.error('删除背景失败:', error)
    ElMessage.error('删除失败，请稍后重试')
  } finally {
    deleteDialog.value.loading = false
    deleteDialog.value.visible = false
    deleteDialog.value.background = null
  }
}

// 视频预览控制
const playVideo = (event) => {
  const video = event.target
  if (video.paused) {
    video.play().catch(err => console.error('视频播放失败:', err))
  }
}

const pauseVideo = (event) => {
  const video = event.target
  if (!video.paused) {
    video.pause()
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''

  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 从URL提取文件名
const formatFilename = (url) => {
  if (!url) return '未命名'

  try {
    const urlObj = new URL(url)
    const pathParts = urlObj.pathname.split('/')
    const filename = pathParts[pathParts.length - 1]

    // 如果有文件名，截取前20个字符显示
    if (filename) {
      return filename.length > 20 ? filename.substring(0, 20) + '...' : filename
    }

    return '未命名'
  } catch (error) {
    return '未命名'
  }
}
</script>

<style scoped>
.background-gallery {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.gallery-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
}

.search-filter {
  display: flex;
  gap: 10px;
  flex: 1;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.filter-select {
  width: 120px;
}

.gallery-content {
  flex: 1;
  margin-bottom: 20px;
  min-height: 400px;
}

.background-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.background-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
  background-color: #f5f7fa;
}

.background-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.background-preview {
  position: relative;
  height: 150px;
  overflow: hidden;
}

.preview-media {
  width: 100%;
  height: 100%;
  object-fit: cover;
  background-color: #ebeef5;
}

.background-actions {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.background-item:hover .background-actions {
  opacity: 1;
}

.background-info {
  padding: 12px;
}

.background-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.background-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.background-date {
  font-size: 12px;
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.gallery-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.delete-confirm {
  text-align: center;
  padding: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>